<?php
/**
 * Created by IntelliJ IDEA.
 * User: HXL
 * Date: 2018/5/9
 * Time: 11:25
 */
namespace app\orders\controller;

use app\common\ErrorCodes;
use think\Lang;

/**
 * 订单评审
 * Class Order
 * @package app\order\controller
 */
class Order extends Base{

    public function index(){
//        $this->authVerify();
        //先从订单表中获取全部信息，mid，在由mid获取表号
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status";
        $where = array('parent_id'=>'0');
        //如果不是业务部门就没有
        $sale_id = session('order_saleid');
        if($sale_id != 0){
            $where['sale_id'] = $sale_id;
        }
        $orders = $this->orders()->joinAll($where);
        $orders = $this->resetOrders($orders);
//        var_dump($orders);exit();
        $this->page($orders);
        $this->asgMeterTypes();
        $this->asgModelTypes();
        $this->asgPros();
        $this->asgFits();
        $this->asgClients();
        //var_dump($order);exit();
        $this->assign('orders', $orders);
        return $this->show($orders);
//        return $this->fetch("ord/index");

    }
    /**
     * 添加action
     */
    public function save(){
        $this->authVerify();
        $orders = input('post.');
        //var_dump($orders);exit();
        $orders['create_time'] = date('Y-m-d H:i:s', time());
        //默认订单状态(生产中)
        $orders['deliver_status'] = 1;
        $fid = $orders['fid'];
        $fidNum = $orders['fid_num'];

        $tempfid = $this->stringToArr($fid);
        $tempNum = $this->stringToArr($fidNum);

        //配件数据处理
        $temp = $this->dealFids($tempfid, $tempNum);
        $fid = $temp['fid'];
        $fidNum = $temp['fid_num'];

        //1.先形成一个主订单
        $parentOrder = $orders;
        $parentOrder['fid'] = '';
        $parentOrder['fid_num'] = '';

        $addParentOrder = $this->orders()->add($parentOrder, '');
        if(!$addParentOrder){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('add fail'));
//            return $this->error(Lang::get('add fail'));
        }
//        var_dump($orders);exit();
        //获取主订单id
        $lastId = $this->orders()->lastSql();
        //2.处理多个基表型号
        $meterIdString = $orders['meter_id'];
        $numString = $orders['order_qty'];
        $orderMeters = $this->dealOrderMeter($meterIdString, $numString);
        for($t=0;$t<count($orderMeters);$t++){
            $orderMeters[$t]['o_id'] = $lastId;
        }
        //多个基表型号信息批量添加到数据库
        $this->orderMeters()->insertAll($orderMeters);
        //3.批量添加（形成子订单）
        $newLen = count($fid);
        //没有子订单时
        if($newLen > 0){
            $insertAll = array();
            for($j=0;$j<$newLen;$j++){
                $insertAll[$j] = $orders;
                //订单执行默认状态：未执行5
                $insertAll[$j]['deliver_status'] = 5;
                $insertAll[$j]['parent_id'] = $lastId;
                $insertAll[$j]['fid'] = $fid[$j];
                $insertAll[$j]['fid_num'] = $fidNum[$j];
            }

            $addOrder = $this->orders()->insertAll($insertAll);
            //TODO
            if(!$addOrder){
                return $this->error(Lang::get('add fail'));
            }
        }
        //成功添加订单审核，发送短信TODO
        $phone = '18642881168';
        //模板参数
        $num = '1234基表';
        $status = '待组装';

        return $this->success(Lang::get('add success'), 'Order/index');

    }

    /**
     * 修改子订单状态action
     */
    public function esave(){
        $this->authVerify();
        $oid = input("param.oid");
        //订单号存在
        $where = array('oid'=>$oid);
        $find = $this->orders()->findById($where);
        if(!$find){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('order unexist'));
//            return $this->error(Lang::get('order unexist'));
        }
        $orders['oid'] = $oid;
        $orders['deliver_status'] = input('param.deliver_status');
        $edit = $this->orders()->update($orders, $where);
        if($edit < 1){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('edit fail'));
//            return $this->error(Lang::get('edit fail'));
        }
        return $this->show($orders, ErrorCodes::$SUCCESS, Lang::get('edit success'));
//        return $this->success(Lang::get('edit success'), 'Order/index');

    }

    /**
     * 修改主表订单action
     */
    public function esavepa(){
        $this->authVerify();
        $orders = input('post.');
        $oid = $orders['oid'];
        $where = array('oid'=>$oid);
        $find = $this->orders()->findById($where);
        if(!$find){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('order unexist'));
//            return $this->error(Lang::get('order unexist'));
        }
        $fid = $orders['fid'];
        $fidNum = $orders['fid_num'];

        $tempfid = $this->stringToArr($fid);
        $tempNum = $this->stringToArr($fidNum);

        //数据处理
        $temp = $this->dealFids($tempfid, $tempNum);
        $fid = $temp['fid'];
        $fidNum = $temp['fid_num'];
//        var_dump($orders);exit();
        //1.先修改主订单信息
        $parentOrder = $orders;
        $parentOrder['fid'] = '';
        $parentOrder['fid_num'] = '';
        $editParentOrder = $this->orders()->update($parentOrder, $where);

        //2.批量修改已有的子订单并添加新加的,删除多余的
        $newLen = count($fid);
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status,sale_id,valve_status";
        //a.有子订单时
        if($newLen > 0){
            $need = $this->setNewChild($oid, $field, $fid);
            //var_dump($need);exit();
            $del = $need['del'];
            //删除多余的
            if(count($del) > 0){
                foreach ($del as $d){
                    $this->orders()->del(array('oid'=>$d));
                }
            }
            //修改原有的
            $edit = $need['edit'];
            if(count($edit) > 0){
                $editResult = $this->updateChild($edit, $fid, $fidNum, $orders);
            }

            //再添加新的
            $add = $need['add'];
            if(count($add) > 0){
                $addOrder = $this->addChild($add, $fid, $fidNum, $orders);
                if((!$addOrder) && (!$editParentOrder)){
                    return $this->show(array(), ErrorCodes::$FAIL, Lang::get('edit fail'));
//                    return $this->error(Lang::get('edit fail'));
                }
            }
        }else{
            //b.没有子订单，删除原有的子订单
            $findChild = $this->orders()->select($field, array('parent_id'=>$oid));
            $childLen = count($findChild);
            //原本有子订单,删除
            if($childLen > 0){
                for($k=0;$k<$childLen;$k++){
                    $childOid = $findChild[$k]['oid'];
                    $this->orders()->del(array('oid'=>$childOid));
                }
            }
        }
        //3.修改基表型号信息
        $meterIdString = $orders['meter_id'];
        $numString = $orders['order_qty'];
        $orderMeters = $this->editOrderMeter($meterIdString, $numString, $oid);
        //a.新添加-》批量添加
        $needAdd = $orderMeters['add'];
        if($needAdd){
            $this->orderMeters()->insertAll($needAdd);
        }
        //b.修改-》循环更新
        $needEdit = $orderMeters['edit'];
        if($needEdit){
            for($editLen = 0;$editLen<count($needEdit);$editLen++){
                //先判断是否需要修改
                $oldOM = $this->orderMeters()->findById(array('om_id'=>$needEdit[$editLen]['om_id']));
                if(!strcmp($oldOM['m_num'], $needEdit[$editLen]['m_num'])){
                    $this->orderMeters()->update($needEdit[$editLen], array('om_id'=>$needEdit[$editLen]['om_id']));
                }
            }
        }
        //c.删除-》 批量删除
        $needDel = $orderMeters['del'];
        if($needDel){
            $this->orderMeters()->del(array('om_id'=>['in', $needDel]));
        }
        return $this->success(Lang::get('edit success'), 'Order/index');
    }

    /**
     * 修改表计订单的状态
     * editpa status
     */
    public function epasta(){
        $this->authVerify();
        $oid = input('param.oid');
        $isStatus = input('param.deliver_status');
        $where = array('oid'=>$oid);
        $find = $this->orders()->findById($where);
        if(!$find){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('order unexist'));
//            return $this->error(Lang::get('order unexist'));
        }
        //改为已完成状态时，需要进行如下判断
        if($isStatus == 0){
            //1.是否有子订单
            $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status,sale_id,valve_status";
            $findChild = $this->orders()->select($field, array('parent_id'=>$oid));
            $childLen = count($findChild);
            if($childLen > 0){
                for($i=0;$i<$childLen;$i++){
                    //2.判断子订单的状态是否都是已完成
                    //3.如果有生产中状态的则不可修改为已完成
                    if($findChild[$i]['deliver_status'] != 0){
                        return $this->show(array(), ErrorCodes::$FAIL, Lang::get('child order no done'));
//                        return $this->error(Lang::get('child order no done'));
                    }
                }
            }
        }
        //4.修改状态
        $order['deliver_status'] = $isStatus;
        $editStatus = $this->orders()->update($order, $where);
        if(!$editStatus){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('edit fail'));
//            return $this->error(Lang::get('edit fail'));
        }
        return $this->show($order, ErrorCodes::$SUCCESS, Lang::get('edit success'));
//        return $this->success(Lang::get('edit success'), 'Order/index');
    }

    /**
     * json数据（一条数据）
     */
    public function one(){
        $oid = input('param.oid');
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status";
        $where = array('oid'=>$oid);
        $data = $this->orders()->joinSelect($where);
        $data = $this->resetOrders($data);
        return $this->show($data);
    }

    /**
     * 主表订单json
     */
    public function onepa(){
        $oid = input('param.oid');
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status,sale_id,valve_status";
        $where = array('oid'=>$oid);
        $find = $this->orders()->select($field, $where);
        $parentId = $find['0']['parent_id'];
        //1.组合配件
        $find['0']['fids'] = array();
        if($parentId == 0){
            //获取子订单
            $findChild = $this->orders()->select($field, array('parent_id'=>$oid));
            $childLen = count($findChild);
            for ($i=0;$i<$childLen;$i++){
                $find['0']['fids'][$i] = array(
                    'fid'=>$findChild[$i]['fid'],
                    'fid_num'=>$findChild[$i]['fid_num']
                );
            }
        }
        //2.组合基表型号+数量
        $meterIds = $find['0']['meter_id'];
        $orderQtys = $find['0']['order_qty'];
        $meterIdArr = $this->stringToArr($meterIds);
        $orderQtyArr = $this->stringToArr($orderQtys);
        $find['0']['meters'] = array();
        if(count($meterIdArr) > 0){
            for($j=0;$j<count($meterIdArr);$j++){
                $find['0']['meters'][$j] = array(
                    'mId'=>$meterIdArr[$j],
                    'mNum'=>$orderQtyArr[$j]
                );
            }
        }
        return $this->show($find);

    }

    /**
     * 删除action
     */
    public function del(){
        $this->authVerify();
        $oid = input('param.oid');
        $where = array('oid'=>$oid);
        $find = $this->orders()->findById($where);
        if(!$find){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('order unexist'));
//            return $this->error(Lang::get('order unexist'));
        }
        //如果是主订单，存在子订单的不可删除
        $parentId = $find['parent_id'];
        if($parentId == 0){
            $findParent = $this->orders()->findById(array('parent_id'=>$oid));
            if($findParent){
                return $this->show(array(), ErrorCodes::$FAIL, Lang::get('child order existed'));
//                return $this->error(Lang::get('child order existed'));
            }
        }

        $del = $this->orders()->del($where);
        if($del < 1){
            return $this->show(array(), ErrorCodes::$FAIL, Lang::get('del fail'));
//            return $this->error(Lang::get('del fail'));
        }
        //删除基表型号联合表信息
        $this->orderMeters()->del(array('o_id'=>$oid));
        return $this->show($find, ErrorCodes::$SUCCESS, Lang::get('del success'));
//        return $this->success(Lang::get('del success'), 'Order/index');
    }

    /**
     * 查看详单
     */
    public function view(){
        $this->authVerify();
        //国家，客户，基表型号，电子模块类型，制造商，生产负责人，发货状态都是下拉框选择
        $oid = input('param.oid');
        $orders = $this->orders()->joinAll(array('oid'=>$oid));
//        var_dump($order);exit();
        $order = $this->detail($orders['0']);
        //配件
        $fids = $order['fids'];
        //基表型号
        $meterIds = $order['meter_id'];
        $meterIdArr = $this->stringToArr($meterIds);
        if(count($meterIdArr) > 0){
            $orderMeters = $this->orderMeters()->join(array('o_id'=>$oid, 'm_id'=>['in', $meterIdArr]));
        }else{
            $orderMeters = array();
        }
        $this->assign('ordermeters', $orderMeters);
        $this->assign('order', $order);
        $this->assign("fids", $fids);
        //TODO
        return $this->fetch("ord/detail");
    }


    /**
     * 搜索
     */
    public function search(){
        $search = input('post.');
        //var_dump($search);exit();
        $client = intval(input('param.client'));
        $proId = input('param.pro_id');
        $status = input('param.deliver_status');
        $orderPlacer = input('param.order_placer');
        $orders = $this->orders()->join($client, $proId, $status, $orderPlacer);
        //var_dump($orders);exit();
        $len = count($orders);
        //存在搜索的结果
        if($len >= 1){
            $orders = $this->resetOrders($orders);
        }
        $this->page($orders);
        $this->asgMeterTypes();
        $this->asgModelTypes();
        $this->asgPros();
        $this->asgFits();
        $this->asgClients();
        //var_dump($orders);exit();
        $this->assign('orders', $orders);
        return $this->show($orders);
//        return $this->fetch("ord/index");

    }

    /**
     * 配件执行
     */
    public function exec(){
        $this->authVerify();
        $where = array('parent_id'=>['>','0']);
        //表计组只能查看自己的订单
        $status = session('order_status');
        $surname = session('order_surname');
        //只能查看自己业务部的订单
        if($status == 3){
            $where['product_principle'] = $surname;
        }
        //如果不是业务部门就没有
        $sale_id = session('order_saleid');
        if($sale_id != 0){
            $where['sale_id'] = $sale_id;
        }
        $orders = $this->orders()->joinExec($where);
        $this->page($orders);
        $this->asgMeterTypes();
        $this->asgModelTypes();
        $this->asgPros();
        $this->asgFits();
        $this->asgClients();
        //var_dump($order);exit();
        $this->assign('orders', $orders);
        return $this->show($orders);
//        return $this->fetch("ord/exec");
    }

    /**
     * 配件执行的搜索
     * @return mixed
     */
    public function searchexec(){
        $cid = input('param.cid');
        $pro_id = input('param.pro_id');
        $deliver_status = input('param.deliver_status');
        $order_placer = input('param.order_placer');
        $where = array();
        //表计组只能查看自己的订单
        $status = session('order_status');
        $surname = session('order_surname');
        //只能查看自己业务部的订单
        if($status == 3){
            $where['product_principle'] = $surname;
        }
        //如果不是业务部门就没有
        $sale_id = session('order_saleid');
        if($sale_id != 0){
            $where['sale_id'] = $sale_id;
        }
        $orders = $this->orders()->searchExec($cid, $pro_id, $deliver_status, $order_placer, $where);
        $this->page($orders);
        $this->asgMeterTypes();
        $this->asgModelTypes();
        $this->asgPros();
        $this->asgFits();
        $this->asgClients();
        //var_dump($order);exit();
        $this->assign('orders', $orders);
        return $this->show($orders);
//        return $this->fetch("ord/exec");
    }
    /**
     * 配件数据的处理
     * @param $fid
     * @param $fidNum
     */
    private function dealFids($tempfid, $tempNum){
        $len = count($tempfid);
        $temp = array(
            'fid'=>array(),
            'fid_num'=>array()
        );
        for ($i=0;$i<$len;$i++){
            $temp['fid'][$i] = $tempfid[$i];
            $temp['fid_num'][$i] = $tempNum[$i];

        }
        $fid = $temp['fid'];
        $fidNum = $temp['fid_num'];
        $fids['fid'] = $fid;
        $fids['fid_num'] = $fidNum;
        return $fids;
    }

    /**
     * 需要修改的子订单信息
     * @param $edit
     * @param $fid
     * @param $fidNum
     * @param $orders
     */
    private function updateChild($edit, $fid, $fidNum, $orders){
        unset($orders['oid']);
        $editOid = $edit['oid'];
        $editFid = $edit['fid'];
        $editResult = 0;
        foreach ($editFid as $k=>$value){
            if($value == $fid[$k]){
                $editOrder = $orders;
                $editOrder['fid'] = $fid[$k];
                $editOrder['fid_num'] = $fidNum[$k];
                //var_dump($editOrder);exit();
                $editResult = $this->orders()->update($editOrder, array('oid'=>$editOid[$k]));
            }
        }
        return $editResult;
    }

    /**
     * 新的fid的批量添加
     * @param $add
     * @param $fid
     * @param $fidNum
     * @param $orders
     * @return array
     */
    private function addChild($add, $fid, $fidNum, $orders){
        $parentId = $orders['oid'];
        unset($orders['oid']);
        $insertAll = array();
        foreach ($add as $k=>$value){
            if($value == $fid[$k]){
                $insertAll[$k] = $orders;
                $insertAll[$k]['create_time'] = date('Y-m-d H:i:s', time());
                $insertAll[$k]['deliver_status'] = 1;
                $insertAll[$k]['parent_id'] = $parentId;
                $insertAll[$k]['fid'] = $fid[$k];
                $insertAll[$k]['fid_num'] = $fidNum[$k];
            }
        }
        //var_dump($insertAll);exit();
        $addOrder = 0;
        $len = count($insertAll);
        if($len > 0){
            foreach ($insertAll as $value){
                $addOrder = $this->orders()->add($value, '');
            }
        }
        return $addOrder;
    }
    /**
     * 获取需要修改、添加、删除的子订单的fid
     * @param $oid
     * @param $field
     * @param $newFid
     * @return mixed
     */
    private function setNewChild($oid, $field, $newFid){
        $where = array('parent_id'=>$oid);
        //1.判断修改的子订单在原先是否存在
        $findChild = $this->orders()->select($field, $where);
        $need = array(
            'del'=>array(),
            'edit'=>array(),
            'add'=>array()
        );
        $oldfid = array(
            'fid'=>array(),
            'oid'=>array()
        );
        //初始化
        $needDel = array();
        $needEdit = array();
        $needAdd = array();
        if(count($findChild) > 0){
            foreach ($findChild as $k=>$value){
                $temp = $value['fid'];
                $oldfid['oid'][$k] = $value['oid'];
                $oldfid['fid'][$k] = $value['fid'];
                //4.多余的，需要删除的oid
                if(!in_array($value['fid'], $newFid)){
                    $needDel[$k] = $value['oid'];
                }
            }
        }
        foreach ($newFid as $key=>$newvalue){
            $ar = $oldfid['fid'];
            //3.不在原始子订单中的,新添加
            if(in_array(intval($newvalue), $ar) == false){
                $needAdd[$key] = $newvalue;
            }
            //2.新订单在原有的订单中存在，修改信息
            foreach ($oldfid['fid'] as $item=>$v){
                if($newvalue == $v){
                    $needEdit['fid'][$key] = $v;
                    $needEdit['oid'][$key] = $oldfid['oid'][$item];
                }
            }

        }

        $need['del'] = $needDel;  //一维 oid
        $need['edit'] = $needEdit;   //二维 oid+fid
        $need['add'] = $needAdd;  //一维 fid
        //var_dump($need);exit();
        return $need;
    }


    /**
     * 二维数组获取
     * @param $orders
     */
    public function resetOrders($orders){
        $len = count($orders);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $orders[$i] = $this->resetOrder($orders[$i]);
            }
        }
        return $orders;
    }

    /**
     * 一维数组获取
     * @param $order
     * @return mixed
     */
    public function resetOrder($order){
        $len = count($order);
        if($len > 0){
            for($i=0;$i<$len;$i++){
                $cid = $order['cid'];
                $fid = $order['fid']; //配件id
                if($fid > 0){
                    $findFit = $this->fittings()->join(array('fid'=>$fid));
                    if($findFit){
                        $order['fitting'] = $findFit['0']['fitting'];
                        $order['principle'] = $findFit['0']['product_principle'];
                    }else{
                        $order['fitting'] = '';
                        $order['principle'] = '';
                    }
                }else{
                    $order['fitting'] = '';
                    $order['principle'] = '';
                }
                $isStatus = $order['deliver_status']; //生产状态
                $order['status'] = $this->getStatus($isStatus);
                $order['valve'] = $this->isOrNo($order['is_valve']);
                $order['sieve'] = $this->isOrNo($order['is_sieve']);
                $order['mark'] = $this->isOrNo($order['is_mark']);
                $order['infrade'] = $this->onOrOff($order['is_infrade']);
                $order['sale'] = $this->setSaleDepts($order['sale_id']);

            }

        }else{
            $order['status'] = '';
            $order['meter_type'] = '';
            //$order['model_type'] = '';
            $order['pro_name'] = '';
            $order['fitting'] = '';
            $order['principle'] = '';

            $order['valve'] = '';
            $order['sieve'] = '';
            $order['mark'] = '';
            $order['infrade'] = '';
            $order['sale'] = '';

        }
        return $order;
    }


    /**
     * 表计订单详情
     * @param $order
     * @return mixed
     */
    private function detail($order){
        $oid = $order['oid'];
        $meterId = $order['meter_id']; //基表id
        $findMeter = $this->meterTypes()->findById(array('meter_id'=>$meterId));
        $isStatus = $order['deliver_status']; //生产状态
        $order['status'] = $this->getStatus($isStatus);
        if(!$findMeter){
            $order['meter_type'] = $findMeter['meter_type'];
        }else{
            //表示没有基表型号
            $order['meter_type'] = "N/A";
        }
        $order['valve'] = $this->isOrNo($order['is_valve']);
        $order['sieve'] = $this->isOrNo($order['is_sieve']);
        $order['mark'] = $this->isOrNo($order['is_mark']);
        $order['infrade'] = $this->onOrOff($order['is_infrade']);

        //搜索子订单(配件信息)
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status,valve_status";
        $where = array('parent_id'=>$oid);
        $findChild = $this->orders()->select($field, $where);
        $childLen = count($findChild);
        $order['fids'] = array(
            array(
                'fid'=>'',
                'fitting'=>'',
                'fid_num'=>''
            )
        );
        if($childLen > 0){
            for ($i=0;$i<$childLen;$i++){
                $order['fids'][$i]['fid'] = $findChild[$i]['fid'];
                $findFid[$i] = $this->fittings()->findById(array('fid'=>$findChild[$i]['fid']));
                $order['fids'][$i]['fitting'] = $findFid[$i]['fitting'];
                $order['fids'][$i]['fid_num'] = $findChild[$i]['fid_num'];
            }
        }
        $order['sale'] = $this->setSaleDepts($order['sale_id']);
        return $order;
    }

    /**
     * 获取基表型号id和数量的二维数组
     * @param $meterIdString
     * @param $numString
     * @return array
     */
    private function dealOrderMeter($meterIdString, $numString){
        $meterIdArr = $this->stringToArr($meterIdString);
        $numArr = $this->stringToArr($numString);
        $len = count($meterIdArr);
        $results = array();
        for($i=0;$i<$len;$i++){
            $results[$i]['m_id'] = $meterIdArr[$i];
            $results[$i]['m_num'] = $numArr[$i];
        }
        return $results;
    }

    /**
     * 获取需要增删改的基表型号联合表信息
     * @param $meterIdString
     * @param $numString
     * @param $oid
     * @return array
     */
    private function editOrderMeter($meterIdString, $numString, $oid){
        $orderMeters = $this->orderMeters()->select('*', array('o_id'=>$oid));
        $meterIdArr = $this->stringToArr($meterIdString);
        $numArr = $this->stringToArr($numString);
        //1.数据库中已存在的基表型号-》修改信息
        $getOrderMeter = $this->orderMeters()->select('*', array('o_id'=>$oid,'m_id'=>['in', $meterIdArr]));
        $needEdit = array();
        foreach ($getOrderMeter as $k=>$value){
            for($i=0;$i<count($meterIdArr);$i++){
                if($value['m_id'] == $meterIdArr[$i]){
                    $needEdit[$k]['om_id'] = $value['om_id'];
                    $needEdit[$k]['m_num'] = $numArr[$i];
                    $needEdit[$k]['m_id'] = $value['m_id'];
                    $needEdit[$k]['o_id'] = $oid;
                }
            }

        }
        //2.原本存在，但是现在没有的-》删除
        $needDel = array();
        $oldMeterIdArr = array();  //数据库中原本就存在的所有m_id的一维数组
        foreach ($orderMeters as $k=>$value){
            if(!in_array($value['m_id'], $meterIdArr)){
                //需要删除的基表型号联合表的id
                $needDel[$k] = $value['om_id'];
            }
            $oldMeterIdArr[$k] = $value['m_id'];
        }

        //3.数据库中不存在的基表型号-》添加
        $needAdd = array();
        foreach ($meterIdArr as $k=>$mId){
            if(!in_array($mId, $oldMeterIdArr)){
                $needAdd[$k]['m_id'] = $mId;
                $needAdd[$k]['m_num'] = $numArr[$k];
                $needAdd[$k]['o_id'] = $oid;
            }
        }
        $needAdd = $this->sortArr($needAdd);
        $needEdit = $this->sortArr($needEdit);
        $needDel = $this->sortArr($needDel);
        $results = array(
            'add'=>$needAdd,
            'edit'=>$needEdit,
            'del'=>$needDel
        );
        return $results;
    }

    /**
     * 测试
     */
    public function editTest(){
        $orders = input('param.');
        unset($orders['/order/order/editTest']);
//        var_dump($orders);exit();
        $oid = $orders['oid'];
        $where = array('oid'=>$oid);
        $find = $this->orders()->findById($where);
        if(!$find){
            return $this->error(Lang::get('order unexist'));
        }
        $fid = $orders['fid'];
        $fidNum = $orders['fid_num'];

        $tempfid = $this->stringToArr($fid);
        $tempNum = $this->stringToArr($fidNum);

        //数据处理
        $temp = $this->dealFids($tempfid, $tempNum);
        $fid = $temp['fid'];
        $fidNum = $temp['fid_num'];
//        var_dump($orders);exit();
        //1.先修改主订单信息
        $parentOrder = $orders;
        $parentOrder['fid'] = '';
        $parentOrder['fid_num'] = '';
        $editParentOrder = $this->orders()->update($parentOrder, $where);

        //2.批量修改已有的子订单并添加新加的,删除多余的
        $newLen = count($fid);
        $field = "oid,parent_id,cid,client_contacts,order_placer,placer_phone,transport,meter_id,meter_len,order_qty,pro_id,fid,fid_num,is_valve,is_sieve,nameplate,is_mark,chain,is_infrade,measure_mode,alarm,overdraft,timezone,crypt,sgc,cry_utk,soft_from,other,create_time,deliver_status,valve_status";
        //a.有子订单时
        if($newLen > 0){
            $need = $this->setNewChild($oid, $field, $fid);
            //var_dump($need);exit();
            $del = $need['del'];
            //删除多余的
            if(count($del) > 0){
                foreach ($del as $d){
                    $this->orders()->del(array('oid'=>$d));
                }
            }
            //修改原有的
            $edit = $need['edit'];
            if(count($edit) > 0){
                $editResult = $this->updateChild($edit, $fid, $fidNum, $orders);
            }


            //再添加新的
            $add = $need['add'];
            if(count($add) > 0){
                $addOrder = $this->addChild($add, $fid, $fidNum, $orders);
                if((!$addOrder) && (!$editParentOrder)){
                    return $this->error(Lang::get('edit fail'));
                }
            }
        }else{
            //b.没有子订单，删除原有的子订单
            $findChild = $this->orders()->select($field, array('parent_id'=>$oid));
            $childLen = count($findChild);
            //原本有子订单,删除
            if($childLen > 0){
                for($k=0;$k<$childLen;$k++){
                    $childOid = $findChild[$k]['oid'];
                    $this->orders()->del(array('oid'=>$childOid));
                }
            }
        }
        //3.修改基表型号信息
        $meterIdString = $orders['meter_id'];
        $numString = $orders['order_qty'];
        $orderMeters = $this->editOrderMeter($meterIdString, $numString, $oid);
        //a.新添加-》批量添加
        $needAdd = $orderMeters['add'];
        if($needAdd){
            $this->orderMeters()->insertAll($needAdd);
        }
        //b.修改-》循环更新
        $needEdit = $orderMeters['edit'];
        if($needEdit){
            for($editLen = 0;$editLen<count($needEdit);$editLen++){
                //先判断是否需要修改
                $oldOM = $this->orderMeters()->findById(array('om_id'=>$needEdit[$editLen]['om_id']));
                if(!strcmp($oldOM['m_num'], $needEdit[$editLen]['m_num'])){
                    $this->orderMeters()->update($needEdit[$editLen], array('om_id'=>$needEdit[$editLen]['om_id']));
                }
            }
        }
        //c.删除-》 批量删除
        $needDel = $orderMeters['del'];
        if($needDel){
            $this->orderMeters()->del(array('om_id'=>['in', $needDel]));
        }
        return $this->success(Lang::get('edit success'), 'Order/index');
    }


}